﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Athena.ProxyGenerator
{
    using Runtime.Client;
    public static class ServiceProxyFactoryExtension
    {

        public static void Initialization(this IServiceProxyFactory serviceProxyFactory, IEnumerable<string> assemblyNames, IEnumerable<string> assemblyPaths)
        {
            var assemblys = new List<Assembly>();
            if (assemblyNames != null)
            {
                foreach (var name in assemblyNames)
                {
                    assemblys.Add(Assembly.Load(name));
                }
            }
            if (assemblyPaths != null)
            {
                foreach (var assemblyPath in assemblyPaths)
                {
                    assemblys.Add(Assembly.LoadFile(assemblyPath));
                }
            }
            if (assemblys.Count <= 0)
            {
                assemblys.AddRange(AppDomain.CurrentDomain.GetAssemblies().Where(x => {
                    return !x.FullName.StartsWith("System") && !x.FullName.StartsWith("Microsoft");
                }));
            }
            serviceProxyFactory.Initialization(assemblys);
        }

        public static void Initialization(this IServiceProxyFactory serviceProxyFactory, IEnumerable<Assembly> assemblys)
        {
            IEnumerable<Type> needProxyTypes = new Type[0];
            var clientServiceProxyKeyTypeOf = typeof(IClientServiceProxyKey);
            foreach (var assembly in assemblys)
            {
                var clientServiceProxyKeyTypes = assembly.GetTypes().Where(x => x.IsInterface && clientServiceProxyKeyTypeOf.IsAssignableFrom(x));
                needProxyTypes = needProxyTypes.Concat(clientServiceProxyKeyTypes);
            }
            serviceProxyFactory.RegisteProxyType(needProxyTypes);
        }
    }
}
